package com.amsp.oa.oademo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.amsp.oa.oademo.entity.TrainingSign;
import com.amsp.oa.oademo.entity.TrainingStudent;
import com.amsp.oa.oademo.mapper.TrainingSignMapper;
import com.amsp.oa.oademo.mapper.TrainingStudentMapper;
import com.amsp.oa.oademo.service.TrainingSignService;
import com.amsp.oa.oademo.vo.TrainingSignVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TrainingSignServiceImpl extends ServiceImpl<TrainingSignMapper, TrainingSign>
        implements TrainingSignService {

    @Resource
    private TrainingStudentMapper trainingStudentMapper;

    @Override
    public IPage<TrainingSignVO> page(Integer current, Integer size, String trainer) {
        Page<TrainingSign> page = new Page<>(current, size);
        LambdaQueryWrapper<TrainingSign> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(trainer)) {
            wrapper.like(TrainingSign::getTrainer, trainer);
        }
        wrapper.orderByDesc(TrainingSign::getCreateTime);

        return baseMapper.selectPage(page, wrapper).convert(this::convertToVO);
    }

    @Override
    public TrainingSignVO getDetail(Long id) {
        TrainingSign trainingSign = getById(id);
        if (trainingSign == null) {
            return null;
        }
        return convertToVO(trainingSign);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateTransactional(TrainingSignVO vo) {
        // 保存主表
        TrainingSign trainingSign = new TrainingSign();
        BeanUtils.copyProperties(vo, trainingSign);

        // 计算统计数据
        if (vo.getStudents() != null && !vo.getStudents().isEmpty()) {
            int totalStudents = (int) vo.getStudents().stream()
                    .filter(student -> student.getSignIn() != null && student.getSignIn())
                    .count();
            int qualifiedStudents = (int) vo.getStudents().stream()
                    .filter(student -> student.getScore() != null && student.getScore() >= 60)
                    .count();

            trainingSign.setTotalStudents(totalStudents);
            trainingSign.setQualifiedStudents(qualifiedStudents);
            if (totalStudents > 0) {
                trainingSign.setPassRate(BigDecimal.valueOf(qualifiedStudents * 100.0 / totalStudents));
            }
        }

        saveOrUpdate(trainingSign);

        // 保存学员信息
        if (vo.getStudents() != null) {
            // 删除旧的学员数据
            if (trainingSign.getId() != null) {
                LambdaQueryWrapper<TrainingStudent> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(TrainingStudent::getTrainingId, trainingSign.getId());
                trainingStudentMapper.delete(wrapper);
            }

            // 保存新的学员数据
            List<TrainingStudent> students = vo.getStudents().stream().map(studentVO -> {
                TrainingStudent student = new TrainingStudent();
                BeanUtils.copyProperties(studentVO, student);
                student.setTrainingId(trainingSign.getId());
                return student;
            }).collect(Collectors.toList());

            if (!students.isEmpty()) {
                students.forEach(trainingStudentMapper::insert);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIdsTransactional(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            // 删除主表数据
            removeByIds(ids);

            // 删除关联的学员数据
            LambdaQueryWrapper<TrainingStudent> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(TrainingStudent::getTrainingId, ids);
            trainingStudentMapper.delete(wrapper);
        }
    }

    private TrainingSignVO convertToVO(TrainingSign entity) {
        if (entity == null) {
            return null;
        }

        TrainingSignVO vo = new TrainingSignVO();
        BeanUtils.copyProperties(entity, vo);

        // 查询关联的学员信息
        LambdaQueryWrapper<TrainingStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TrainingStudent::getTrainingId, entity.getId());
        List<TrainingStudent> students = trainingStudentMapper.selectList(wrapper);

        if (students != null && !students.isEmpty()) {
            vo.setStudents(students.stream().map(student -> {
                TrainingSignVO.TrainingStudentVO studentVO = new TrainingSignVO.TrainingStudentVO();
                BeanUtils.copyProperties(student, studentVO);
                return studentVO;
            }).collect(Collectors.toList()));
        }

        return vo;
    }
}